<?php
/**
 * WebProduction Shop (wpshop)
 * @copyright (C) 2011-2012 WebProduction (tm) <webproduction.com.ua>
 *
 * This program is commercial software; you cannot redistribute it and/or
 * modify.
 */

class User extends XUser {

    public function __construct($id = 0) {
        parent::__construct($id);
        $this->setClassname(__CLASS__);
    }

    /**
     * @return User
     */
    public static function Get($key) {
        return self::GetObject("User", $key);
    }

    /**
     * @return User
     */
    public function getNext() {
        return parent::getNext();
    }

    /**
     * @return array
     */
    public function makeInfoArray() {
        $a = array();
        $a['login'] = $this->getLogin();
        $a['name'] = htmlspecialchars($this->getName());
        $a['phone'] = htmlspecialchars($this->getPhone());
        //$a['email'] = htmlspecialchars($this->getEmail());
        //$a['url'] = $this->makeURLEdit();
        //$a['avatar'] = $this->makeImageGravatar();
        return $a;
    }

    public function makeURLEdit() {
        return Engine::GetLinkMaker()->makeURLByContentIDParam(
        'admin-users-control',
        $this->getId()
        );
    }

    /**
     * Является ли юзер менеджером или админом?
     *
     * @return bool
     */
    public function isAdmin() {
        return ($this->getLevel() >= 2);
    }

    /**
     * Проверить, разрешен ли пользователю доступ к ACL-ключу $permissionKey
     *
     * @param string $permissionKey
     * @return bool
     */
    public function isAllowed($permissionKey) {
        try {
            $user = $this;
            if ($user->getLevel() >= 3) {
                return true;
            }
            $role = 'user'.$user->getId();
            return BC::Get()->getUserService()->getUserACL($user)->isAllowed(
            $role,
            $permissionKey
            );
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Проверить, запрещен ли пользователю доступ к ACL-ключу $permissionKey
     *
     * @param string $permissionKey
     * @return bool
     */
    public function isDenied($permissionKey) {
        return !$this->isAllowed($permissionKey);
    }

    /**
     * Построить URL на Gravatar
     *
     * @param int $size
     * @return string
     */
    public function makeImageGravatar($size = 50) {
        return "http://www.gravatar.com/avatar/".md5(strtolower($this->getEmail()))."?s=".$size;
    }

    /**
     * @param int $width
     * @param bool $height
     * @param string $method
     * @return bool|mixed
     */
    public function makeImageThumb($width = 60, $height = 60, $method = 'cut') {
        $src = $this->getImage();
        $dir = MEDIA_PATH . 'users/'.$this->getId().'/';
        if (!$src || !file_exists($dir . $src)) {
            return;
        } else {
            $src = MEDIA_PATH . 'users/' . $this->getId().'/' . $src;
            PackageLoader::Get()->import('ImageProcessor');
            if ($method == 'prop') {
                $x = ImageProcessor_Thumber::MakeThumbProportional($src, $width, $height);
            } else {
                $x = ImageProcessor_Thumber::MakeThumbCrop($src, $width, $height);
            }
            $x = str_replace(PROJECT_PATH, '/', $x);
            return $x;
        }
    }

    /**
     * Получить валюту пользователя.
     * Если валюта не указана - будет выставлена системная.
     *
     * @return ShopCurrency
     */
    public function getCurrency() {
        $currencyID = $this->getCurrencyid();
        if (!$currencyID) {
            try {
                SQLObject::TransactionStart();

                $currencyID = BC::Get()->getCurrencyService()->getCurrencySystem()->getId();
                $this->setCurrencyid($currencyID);
                $this->update();

                SQLObject::TransactionCommit();
            } catch (Exception $ge) {
                SQLObject::TransactionRollback();
                throw $ge;
            }
        }

        return BC::Get()->getCurrencyService()->getCurrencyByID($currencyID);
    }

    /**
     * Получить финансовые транзакции пользователя
     *
     * @return ShopCash
     */
    public function getCashTransactions() {
        return BC::Get()->getCashService()->getUserTransactions($this);
    }

    /**
     * @return User
     */
    public function getManager() {
        return BC::Get()->getUserService()->getUserByID($this->getManagerid());
    }

    /**
     * Посчитать баланс в указанной валюте.
     *
     * Метод править разрешено только Senior'ам!
     *
     * @param ShopCurrency $currency
     * @return float
     */
    public function makeBalance(ShopCurrency $currency) {
        $balance = $this->getBalance();

        $balance = BC::Get()->getCurrencyService()->convertCurrency(
            $balance,
            $this->getCurrency(),
            $currency
        );

        $round = BC::Get()->getSettingsService()->getSettingValue('price-rounding-off');
        if ($round) {
            $balance = round($balance);
        }

        return $balance;
    }

    public function makeNameFull() {
        return $this->getName() ? $this->getName() : $this->getLogin();
    }
}